package cn.wolfcode.p2p.business.controller;

import cn.wolfcode.p2p.anno.NeedLogin;
import cn.wolfcode.p2p.base.query.BidRequestQueryObject;
import cn.wolfcode.p2p.base.query.CreditTransferQueryObject;
import cn.wolfcode.p2p.business.service.IBidRequestService;
import cn.wolfcode.p2p.business.service.ICreditTransferService;
import cn.wolfcode.p2p.util.Constant;
import cn.wolfcode.p2p.util.JSONResultUtil;
import cn.wolfcode.p2p.util.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;

/**
 * 投资
 */
@Controller
public class InvestController {
    @Autowired
    private IBidRequestService bidRequestService;
    @Autowired
    private ICreditTransferService creditTransferService;


    /**
     * 投资页面
     */
    @RequestMapping("invest")
    public String invest(){
        return "invest";
    }

    /**
     * 投资列表
     */
    @RequestMapping("/invest_list")
    public String investList(Model model, BidRequestQueryObject qo){
        if (qo.getBidRequestType() == Constant.BIDREQUEST_TYPE_NORMAL) {
            qo.setPageSize(Constant.ANNOUNCEMENT_PAGE_SIZE);
            if(qo.getBidRequestState() == -1){
                qo.setBidRequestStates(new int[]{Constant.BIDREQUEST_STATE_BIDDING,Constant.BIDREQUEST_STATE_PAYING_BACK,Constant.BIDREQUEST_STATE_COMPLETE_PAY_BACK});
            }else{
                qo.setBidRequestState(qo.getBidRequestState());
            }
            qo.setOrderBy(Order.ORDERBY_COLUMN_BID_REQUEST_STATE.orderBy);
            model.addAttribute("pageResult",bidRequestService.investList(qo));
            return "invest_list";
        }else{
            CreditTransferQueryObject queryObject = new CreditTransferQueryObject();
            queryObject.setBidRequestState(Constant.BIDREQUEST_STATE_BIDDING);
            model.addAttribute("pageResult",creditTransferService.queryCreditTransferForPage(queryObject));
            return "credittransfer_list";
        }
    }

    /**
     * 投标
     * @param bidRequestId 借款对象id
     * @param amount 投标金额
     * @return
     */
    @NeedLogin
    @RequestMapping("borrow_bid")
    @ResponseBody
    public Object borrowBid(Long bidRequestId, BigDecimal amount,Integer bidRequestType){
        if(bidRequestType == Constant.BIDREQUEST_TYPE_NORMAL){
            bidRequestService.bidding(bidRequestId,amount);
        }else {
            bidRequestService.expBidding(bidRequestId,amount);
        }
        return JSONResultUtil.jsonResult();
    }
}
